package com.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.common.Result;
import com.springboot.entity.Category;
import com.springboot.entity.Users;
import com.springboot.mapper.CategoryMapper;
import com.springboot.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.springboot.utils.CustomStringUtils;
import com.springboot.utils.IntegerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品分类表 服务实现类
 *
 * @author zjb
 * @since 2025-10-18
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    /**
     * 添加商品分类
     *
     * @param category 分类信息
     * @return 结果
     */
    @Override
    public Result addCategory(Category category) {
        if (!StringUtils.hasText(category.getCategoryName())) {
            return Result.error("分类名称不能为空");
        }
        if (IntegerUtils.isEmptyOrZero(category.getParentId())) {
            return Result.error("父级分类id不能为空或非法值");
        }
        //同一父类下不允许添加同名分类
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getCategoryName, category.getCategoryName())
                .eq(Category::getParentId, category.getParentId());
        if (count(queryWrapper) > 0) {
            return Result.error("同一父类下不允许添加同名分类");
        }
        if (save(category)) {
            return Result.success("添加成功");
        } else {
            return Result.error("添加失败");
        }
    }

    /**
     * 删除商品分类
     *
     * @param categoryId 分类id
     * @return 删除结果
     */
    @Override
    public Result deleteCategory(Integer categoryId) {
        if (IntegerUtils.isEmptyOrZero(categoryId)) {
            return Result.error("分类id不能为空或非法值");
        }
        List<Category> categories = list(new LambdaQueryWrapper<Category>().eq(Category::getParentId, categoryId));
        if (!categories.isEmpty()) {
            return Result.error("请先删除该分类下的子分类");
        }
        if (removeById(categoryId)) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 修改商品分类
     *
     * @param category 分类信息
     * @return 修改结果
     */
    @Override
    public Result updateCategory(Integer categoryId,Category category) {
        if (IntegerUtils.isEmptyOrZero(categoryId)) {
            return Result.error("分类id不能为空或非法值");
        }
        category.setCategoryId(categoryId);
        if (CustomStringUtils.isEmpty(category.getCategoryName())) {
            return Result.error("分类名称不能为非法值");
        }
        if (IntegerUtils.isEmpty(category.getParentId())) {
            return Result.error("父级分类id不能为非法值");
        }
        Category oldCategory = getById(category.getCategoryId());
        if (oldCategory == null) {
            return Result.error("分类不存在");
        }
        boolean nameChanged = !Objects.equals(category.getCategoryName(), oldCategory.getCategoryName());
        boolean parentIdChanged = !Objects.equals(category.getParentId(), oldCategory.getParentId());
        boolean sortChanged = !Objects.equals(category.getSort(), oldCategory.getSort());

        if (nameChanged || parentIdChanged || sortChanged) {
            LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(Category::getParentId, category.getParentId());
            List<Category> categories = list(lambdaQueryWrapper);
            for (Category categoryName : categories) {
                if (Objects.equals(categoryName.getCategoryName(), category.getCategoryName())) {
                    return Result.error("同一父类下不允许存在同名分类");
                }
            }
        }else {
            return Result.error("未修改任何值");
        }

        if (updateById(category)) {
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 查询所有商品分类(树状)
     *
     * @return 商品分类列表
     */
    @Override
    public Result getCategoryAll(Integer pageNum,Integer pageSize) {
        // 获取所有分类
        List<Category> allCategories = list();

        // 构建完整的树状结构
        List<Category> rootCategories = buildCategoryTree(allCategories, 0);
        
        // 对树状结构进行分页
        int total = rootCategories.size();
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);
        
        // 获取当前页数据
        List<Category> pageCategories = new ArrayList<>();
        if (startIndex < total) {
            pageCategories = rootCategories.subList(startIndex, endIndex);
        }
        
        // 创建包含分页信息的结果对象
        java.util.Map<String, Object> resultData = new java.util.HashMap<>();
        resultData.put("categories", pageCategories);
        resultData.put("total", total);
        resultData.put("pageNum", pageNum);
        resultData.put("pageSize", pageSize);
        
        // 返回分页结果
        return Result.success(resultData, "查询成功");
    }

    /**
     * 获取分类列表和层级关系
     *
     * @return 分类列表和层级关系
     */
    @Override
    public Result getCategoryWithHierarchy() {
        // 获取所有分类
        List<Category> allCategories = list();
        
        // 构建层级关系映射
        Map<String, List<Integer>> hierarchy = new HashMap<>();
        for (Category category : allCategories) {
            String parentId = String.valueOf(category.getParentId());
            if (!hierarchy.containsKey(parentId)) {
                hierarchy.put(parentId, new ArrayList<>());
            }
            hierarchy.get(parentId).add(category.getCategoryId());
        }
        
        // 组装最终结果
        Map<String, Object> result = new HashMap<>();
        result.put("categories", allCategories);
        result.put("hierarchy", hierarchy);
        
        return Result.success(result, "查询成功");
    }

    /**
     * 获取级联选择器格式的分类数据
     *
     * @return 级联选择器格式的分类数据
     */
    @Override
    public Result getCategoryForCascader() {
        // 获取所有分类
        List<Category> allCategories = list();
        
        // 构建级联选择器格式的数据
        List<Map<String, Object>> cascaderData = buildCascaderTree(allCategories, 0);
        
        return Result.success(cascaderData, "查询成功");
    }

    /**
     * 构建级联选择器格式的树状结构
     *
     * @param categories 所有分类
     * @param parentId   父级ID
     * @return 级联选择器格式的树状结构
     */
    private List<Map<String, Object>> buildCascaderTree(List<Category> categories, Integer parentId) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        // 筛选出指定父ID的分类
        List<Category> children = categories.stream()
                .filter(category -> category.getParentId().equals(parentId))
                .sorted((c1, c2) -> c1.getSort().compareTo(c2.getSort()))
                .collect(Collectors.toList());
        
        // 为每个子分类构建级联选择器格式
        for (Category category : children) {
            Map<String, Object> cascaderNode = new HashMap<>();
            cascaderNode.put("value", category.getCategoryId());
            cascaderNode.put("label", category.getCategoryName());
            
            // 递归构建子节点
            List<Map<String, Object>> childNodes = buildCascaderTree(categories, category.getCategoryId());
            if (!childNodes.isEmpty()) {
                cascaderNode.put("children", childNodes);
            }
            
            result.add(cascaderNode);
        }
        
        return result;
    }

    /**
     * 构建分类树状结构
     *
     * @param categories 所有分类
     * @param parentId   父级ID
     * @return 树状结构的分类列表
     */
    private List<Category> buildCategoryTree(List<Category> categories, Integer parentId) {
        // 筛选出指定父ID的分类
        return categories.stream()
                .filter(category -> category.getParentId().equals(parentId))
                .peek(category -> {
                    // 递归设置子分类
                    List<Category> children = buildCategoryTree(categories, category.getCategoryId());
                    category.setChildren(children);
                })
                .sorted((c1, c2) -> c1.getSort().compareTo(c2.getSort()))
                .collect(Collectors.toList());
    }

    /**
     * 查询是否为叶子分类
     * @param categoryId 分类id
     * @return 布尔值
     */
    public boolean isLeafCategory(Integer categoryId){
        LambdaQueryWrapper<Category> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Category::getParentId,categoryId);
        List<Category> categories=list(lambdaQueryWrapper);
        return categories == null;
    }
}